package com.mifengkong.frwidget.update.download;

import android.support.annotation.Nullable;
import android.util.Log;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

/**
 * Created by Wang on 2017/6/15
 */

public class ProgressResponseBody extends ResponseBody {
    ResponseBody mResponseBody;
    BufferedSource mBufferedSource;
    ProgressResponseListener mResponseListener;
    DownloadFailListener mDownloadFailListener;

    public ProgressResponseBody(ResponseBody responseBody, ProgressResponseListener responseListener, DownloadFailListener downloadFailListener) {
        this.mResponseBody = responseBody;
        this.mResponseListener = responseListener;
        this.mDownloadFailListener = downloadFailListener;
    }

    @Nullable
    @Override
    public MediaType contentType() {
        return mResponseBody.contentType();
    }

    @Override
    public long contentLength() {
        return mResponseBody.contentLength();
    }

    @Override
    public BufferedSource source() {
        if (mBufferedSource == null) {
            mBufferedSource = Okio.buffer(source(mResponseBody.source()));
        }
        return mBufferedSource;
    }

    private Source source(Source source) {
        return new ForwardingSource(source) {
            long currentRad = 0l;
            long count = 0l;

            @Override
            public long read(Buffer sink, long byteCount) {
                long read = 0;
                try {
                    read = super.read(sink, byteCount);
                    if (count == 0) {
                        count = mResponseBody.contentLength();
                    }

                    currentRad += read != -1 ? read : 0;
                    if (mResponseListener != null) {
                        mResponseListener.onResponseProgress(currentRad, count);
                        if(read == -1) {
                            mResponseListener.onResponseFinish();
                        }
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                    if(mDownloadFailListener != null){
                        mDownloadFailListener.downloadFail(e);
                    }
                }
                return read;
            }
        };
    }
}